package org.lqk.pool.socket2;


import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

public class PooledSocketConnectionFactory implements PooledObjectFactory<SocketConnection> {

	private String host;
	private int port;
	
	public PooledSocketConnectionFactory(SocketConnectionConfig config){
		this.host = config.getHost();
		this.port = config.getPort();
	}

	@Override
	public PooledObject<SocketConnection> makeObject() throws Exception {
		GenericSocketConnection connection = new GenericSocketConnection(host, port);
		return new DefaultPooledObject<SocketConnection>(connection);
	}

	@Override
	public void destroyObject(PooledObject<SocketConnection> p) throws Exception {
		SocketConnection connection = p.getObject();
		connection.destory();

	}

	@Override
	public boolean validateObject(PooledObject<SocketConnection> p) {
		SocketConnection connection = p.getObject();
		if(connection.isClosed()){
			return false;
		}
		return true;
	}

	@Override
	public void activateObject(PooledObject<SocketConnection> p) throws Exception {
		SocketConnection connection = p.getObject();
		if(null == connection || connection.isClosed()){
			connection = new GenericSocketConnection(host, port);
		}
		// 清掉读写缓冲区
		connection.socket().getOutputStream().flush();
//		InputStream in = connection.socket().getInputStream();
//		byte[] b = new byte[1024];
//		int len = -1;
//		while((len = in.read(b)) > -1){}
	}

	@Override
	public void passivateObject(PooledObject<SocketConnection> p) throws Exception {
		SocketConnection connection = p.getObject();
		// 清掉读写缓冲区
		connection.socket().getOutputStream().flush();
//		InputStream in = connection.socket().getInputStream();
//		byte[] b = new byte[1024];
//		int len = -1;
//		while((len = in.read(b)) != -1){}
	}

}
